﻿using System.ServiceModel;
using System.ServiceModel.Activation;
using SurfaceInteraction.MetaData;
using SurfaceInteraction.MetaData.ServiceContract;
using System.ComponentModel;
using System;
using System.Collections;

namespace SurfaceInteraction.Services.Implementation
{
    [ServiceBehavior(Namespace = Schemas.SURFACEINTERACTION_SERVICE_SCHEMA, InstanceContextMode = InstanceContextMode.Single)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class FileExchangeService : IFileExchange, INotifyFileExchange
    {
        private Hashtable images = new Hashtable();

        public void DownloadRequest(int id, Guid imageId)
        {
            RaiseDownloadRequest(id, imageId);
        }

        public byte[] Download(Guid imageId)
        {
            byte[] retVal = null;
            lock (images.SyncRoot)
            {
                if (images.Contains(imageId))
                {
                    retVal = images[imageId] as byte[];
                    images.Remove(imageId);
                }
            }

            return retVal;
        }

        public void Upload(int id, byte[] file)
        {
            RaisUploadRequest(id);
        }


        #region Upload event
        public event UploadRequestEventHandler UploadRequestEvent;

        protected virtual void OnUploadRequest(FileExchangeRequestEventArgs e)
        {
            var handler = this.UploadRequestEvent;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected void RaisUploadRequest(int id)
        {
            OnDownloadRequest(new FileExchangeRequestEventArgs(id));
        }
        #endregion

        #region Download Event
        public event DownloadRequestEventHandler DownloadRequestEvent;
        
        protected virtual void OnDownloadRequest(FileExchangeRequestEventArgs e)
        {
            var handler = DownloadRequestEvent;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected void RaiseDownloadRequest(int id, Guid imageId)
        {
            OnDownloadRequest(new FileExchangeRequestEventArgs(id, imageId));
        }
        #endregion

        public void SendImage(Guid imageId, byte[] image)
        {
            lock (images.SyncRoot)
            {
                if (images.Contains(imageId))
                    images[imageId] = image;
                else
                    images.Add(imageId, image);
            }
        }
    }
}
